package com.xyy.saas.payment.util.xydSign;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author wangzeqi
 */
@Slf4j
public class XydSignUtil {

    public static String sign(String bizParam, String timestamp, String privateKey) throws Exception {
        String signData = EncryptUtils.getMd5SignData(timestamp, bizParam);
        String sign;
        try {
            sign = EncryptUtils.sign(signData.getBytes(), privateKey, EncryptUtils.KEY_SHA_RSA);
            return sign;
        } catch (Exception e) {
            log.error("XydSignUtil sign error, bizParam:{}, timestamp:{}", bizParam, timestamp, e);
            throw e;
        }
    }

    public static boolean verifySign(String response, String publicKey) {
        JSONObject jsonResp = JSON.parseObject(response);
        String accessKey = jsonResp.getString("accessKey");
        String timestamp = jsonResp.getString("timestamp");
        String sign = jsonResp.getString("sign");
        String body = jsonResp.getString("data");

        if (StringUtils.isBlank(sign)) {
            // 部分接口响应报文不加签
            return true;
        }

        try {
            return EncryptUtils.verify(publicKey, timestamp, body, sign);
        } catch (Exception e) {
            log.error("XydSignUtil signVerify error, response:{}", response, e);
            return false;
        }
    }

}
